package com.xie.o2o.service.impl;

import com.xie.o2o.cache.JedisUtil;
import com.xie.o2o.dao.HeadLineDao;
import com.xie.o2o.entity.HeadLine;
import com.xie.o2o.service.HeadLineService;
import com.xie.o2o.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @create: xie
 */
@Service
public class HeadLineServiceImpl implements HeadLineService {
    @Autowired
    private HeadLineDao headLineDao;
    @Autowired
    private JedisUtil.Keys jediskeys;
    @Autowired
    private JedisUtil.Strings jedisStrings;


    /**
     * 获取头条列表
     *
     * @param headLine
     * @return
     */
    @Override
    @Transactional
    public List<HeadLine> getHeadLineList(HeadLine headLine) {
        //设置redis存储的key
        String key = HLLISTKEY;
        List<HeadLine> headLineList = null;
        String s;
        //拼接redis的key
        if (headLine != null && headLine.getEnableStatus() != null) {
            key = key + "_" + headLine.getEnableStatus();
        }
        //判断key是否存在
        if (!jediskeys.exists(key)) {
            //不存在，则从数据库获取
            headLineList = headLineDao.queryHeadLine(headLine);
            //将数据转换成string
            s = JsonUtil.obj2String(headLineList);
            //缓存到redis
            jedisStrings.set(key, s);
        } else {
            //从redis获取
            s = jedisStrings.get(key);
            headLineList = JsonUtil.string2Obj(s, ArrayList.class, HeadLine.class);
        }
        return headLineList;
    }
}
